package com.gk.carshopsys.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gk.carshopsys.pojo.Car;
import com.gk.carshopsys.pojo.Cust;
import com.gk.carshopsys.service.CarService;
import com.gk.carshopsys.service.CustService;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;


public class CarDataListener extends AnalysisEventListener<Car> {

    private CarService carService;

    public CarDataListener(CarService carService) {
        this.carService = carService;
    }

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<Car> list = new ArrayList<Car>();

    @Override
    public void invoke(Car data, AnalysisContext context) {
        System.out.println("解析到一条数据:{}"+data.toString());
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        System.out.println("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        System.out.println("{}条数据，开始存储数据库！"+list.size());
        if (!CollectionUtils.isEmpty(list)) {
            carService.addCarByList(list);
        }
        System.out.println("存储数据库成功！");
    }

}
